import React, { Key, useEffect, useState } from "react";
import {
  Card,
  Col,
  Row,
  Tree,
  Tag,
  Pagination,
  Table,
  Button,
  message,
} from "antd";
import { useNavigate, useParams } from "react-router-dom";
//api
import {
  getHosDepartmentRequest,
  gethosScheduleRuleRequest,
  getFindScheduleListRequest,
} from "@api/hospital/hospitalList";
//type
import type {
  hosDepartmentListType,
  bookingScheduleListType,
  findScheduleListType,
} from "@api/hospital/model/hospitalList";

export default function HospitalSchedule() {
  const Navigate = useNavigate();
  //id
  const { id } = useParams();
  //tree结构数据初始状态
  const [treeData, setTreeData] = useState<hosDepartmentListType>([]);
  //页码初始状态
  const [page, setPage] = useState(1);
  //每页条数
  const [limit, setLimit] = useState(3);
  //数据总数量
  const [total, setTotal] = useState(0);
  //科室详细时间
  const [Schedule, setSchedule] = useState<bookingScheduleListType>([]);
  //table
  const [ScheduleRule, setScheduleRule] = useState<findScheduleListType>([]);
  //depcode
  const [depcode, setDepCode] = useState("");
  //workDate
  const [workDate, setWorkDate] = useState("");
  //isLoading
  const [isLoading, setIsLoading] = useState(false);
  //初始化请求科室列表
  const getDepartment = async () => {
    const result = await getHosDepartmentRequest(id as string);
    setTreeData(result);
    return result;
  };
  //科室排班
  const gethosSchedule = async (
    depcode: string,
    page: number,
    limit: number
  ) => {
    const result = await gethosScheduleRuleRequest({
      page: page,
      limit: limit,
      hoscode: id as string,
      depcode: depcode,
    });
    setSchedule(result.bookingScheduleList);
    setTotal(result.total);
    return result;
  };
  //科室详情
  const getScheduleRule = async (workDate: string, depcode: string) => {
    const result = await getFindScheduleListRequest({
      hoscode: id as string,
      depcode: depcode,
      workDate: workDate,
    });
    setScheduleRule(result);
  };
  useEffect(() => {
    const getData = async () => {
      //目的 当请求完科室列表 在请求单个科室详细时间 在请求详细的排班列表 依次执行
      const departmentValue = await getDepartment();
      //拿到科室列表请求的返回值中的depcode传递
      const depcode = (departmentValue[0].children as hosDepartmentListType)[0]
        .depcode;
      setDepCode(depcode);
      //通过函数传参方式  把科室列表请求的数据传递给 单个科室请求函数
      const hosScheduleValue = await gethosSchedule(depcode, page, limit);
      //拿到workDate 传递给排班列表
      const workDate = hosScheduleValue.bookingScheduleList[0].workDate;
      setWorkDate(workDate);
      await getScheduleRule(workDate, depcode);
    };

    getData();
  }, []);

  //treestyle
  const treeStyle = {
    border: "1px solid #000",
    height: "500px",
    overflow: "auto",
  };
  //table结构数据
  const columns = [
    {
      title: "序号",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "可预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "挂号费用",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];
  //分页事件
  const changeCurrentHandle = async (page: number, limit: number) => {
    setPage(page);
    setLimit(limit);
    //发送科室排班请求
    const result = await gethosSchedule(depcode, page, limit);
    //根据科室排班请求数据第一个请求详细信息
    const newWorkDate = result.bookingScheduleList[0].workDate;
    setWorkDate(newWorkDate);
    getScheduleRule(newWorkDate, depcode);
  };
  //点击树节点触发事件
  const treeHandle = async (depcodeArr: Key[]) => {
    setIsLoading(true);
    if (depcodeArr.length === 0) {
      return;
    }
    try {
      const newdepCode = depcodeArr[0] as string;
      setDepCode(newdepCode);
      //根据点击的值再次发送请求
      const scheudleRule = await gethosSchedule(newdepCode, page, limit);
      //拿到新的workdate 再次去请求
      const newWorkDate = scheudleRule.bookingScheduleList[0].workDate;
      //根据第一个科室排班信息 获取表格详细信息
      getScheduleRule(newWorkDate, newdepCode);
    } catch (e) {
      message.error("没有数据");
      //清空表格
      setScheduleRule([]);
    }
    setIsLoading(false);
  };
  //点击时间详细事件
  const scheduleRuleHandle = (workDate: string) => {
    //console.log(workDate, "workDate");
    return () => {
      setWorkDate(workDate);
      getScheduleRule(workDate, depcode);
    };
  };
  return (
    <Card>
      <p>选择:北京协和医院/多发性硬化专科门诊/2022-04-08</p>
      <Row gutter={20}>
        <Col span={5}>
          <div>
            <Tree
              treeData={treeData as []}
              style={treeStyle}
              fieldNames={{ title: "depname", key: "depcode" }}
              //默认展开
              expandedKeys={["a4e171f4cf9b6816acdfb9ae62c414d7"]}
              onSelect={treeHandle}
            />
          </div>
        </Col>
        <Col span={19}>
          <div style={{ marginBottom: "20px" }}>
            {Schedule.map((item) => {
              //时间
              return (
                <Tag
                  key={item.workDate}
                  onClick={scheduleRuleHandle(item.workDate)}
                  style={{
                    cursor: "pointer",
                    background: item.workDate === workDate ? "#1DA57A" : "",
                  }}
                >
                  <p>{item.workDate}</p>
                  <p>
                    {item.availableNumber}/{item.reservedNumber}
                  </p>
                </Tag>
              );
            })}
          </div>
          <Pagination
            total={total}
            current={page}
            pageSize={limit}
            onChange={changeCurrentHandle}
          />

          <Table
            columns={columns}
            dataSource={ScheduleRule}
            style={{ marginTop: "20px" }}
            rowKey={"id"}
            pagination={false}
            loading={isLoading}
          ></Table>
          <Button style={{ marginTop: "20px" }} onClick={() => Navigate(-1)}>
            返回
          </Button>
        </Col>
      </Row>
    </Card>
  );
}
